package com.maoyan.quickdevelop.common.utils;

import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.util.Optional;
import java.util.UUID;

public class UploadFile {

    public static String upload(MultipartFile file) throws IOException {
        String s = UUID.randomUUID().toString().replace("-", "");
        //获取文件名字
        String fileName = s + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //设置编译后文件存在路径
        String path1 = URLDecoder.decode(ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/uploadFiles/", "utf-8");
        //获取项目路径
        File directory = new File("src/main/resources/static/uploadFiles");
        String paths = directory.getCanonicalPath();
        File dest = new File(paths + '/' + fileName);
        System.out.println(dest.getAbsoluteFile());
        InputStream inputStream = file.getInputStream();
        //以流的方式上传
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path1 + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = inputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        try {
            //文件上传
            file.transferTo(dest);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return "http://localhost:8080/uploadFiles/" + fileName;
    }
}
